package lc20240601;

import lc20240521.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 计算二叉搜索树的最小差值。
 * @date 2024/6/1 15:24
 */
public class getMinBinaryTree {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.right = new TreeNode(6);
        root.left = new TreeNode(2, new TreeNode(1), new TreeNode(3));
        System.out.println(getMinimum(root));
    }

    public static int getMinimumDifference(TreeNode root) {

        List<Integer> integerList = new ArrayList<>();
        inOrder(root, integerList);
//        System.out.println(integerList);
        int min = integerList.get(1) - integerList.get(0);
        for (int i = 0; i < integerList.size() - 1; i++) {
            int temp = integerList.get(i + 1) - integerList.get(i);
            min = min < temp ? min : temp;
        }
        return min;
    }

    private static void inOrder(TreeNode node, List<Integer> list) {
//        List<Integer> list=new ArrayList<>();
        if (node == null) {
            return;
        }
        inOrder(node.left, list);
        list.add(node.val);
        inOrder(node.right, list);
    }

    static TreeNode prev;
    static int min = Integer.MAX_VALUE;

    //在中序遍历的过程中，计算最小值。
    public static int getMinimum(TreeNode root) {

        inOrder(root);
        return min;
    }

    public static void inOrder(TreeNode node) {
        if (node == null) {
            return;
        }
        inOrder(node.left);
        if (prev != null) {
            min = Math.min(min, node.val - prev.val);
        }
        prev = node;
        inOrder(node.right);
    }
}
